package com.bodacn.keypoint;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentO extends Fragment implements View.OnClickListener {
    public static final int msgFocusBarcode = 1001;
    public static final int msgGetImg = 1002;
    public static final int msgShowImage =1003;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_DETAIL = 9002;
    public static final int MSG_MEASURE=9003;
    public static final int MSG_PROCRESULT=9004;
    public static final int MSG_GETPLACE=9005;
    public static final int MSG_GETPATH=9006;
    public static final int MSG_PUTNEXT=9007;
    public static final int MSG_AGVREC=9008;
    public static final int MSG_AREADETAIL=9009;
    public static final int MSG_TASK=9010;
    public static final int MSG_RACKDETAIL=9011;
    public static final int MSG_NEEDCLEAR=9012;
    public static final int MSG_CLEARBIND =9013;
    public static final int MSG_ERRMSG = 9999;

    public static String TAG= FragmentN.class.getName();
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Button btn_Refresh;
    ListView lv_task;
    LinearLayout templetlisthead;
    ListView selectTempletList;
    TextView txt_HintInfo;
    Toast curToast;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    String selRackCode;
    String NeedClearRack="",curAreaCode="";
    GridView lineGrid,storageGrid;
    //其他变量
    JSONArray detailJSON, questionJSON,  itemTypeJSON, itemDetailJSON, measureJSON,procRstJSON,placeJSON,resultJSON,pathJSON,headJSON;
    JSONArray rackDetailJSON,areaJSON,lineJson,storageJson,taskJson;
    String selLinePlace="",selHousePlace="",SelAreaCode="";
    Integer curAgvReqIndex=0,selTaskIndex=0;
    TextView txt_SourceArea,txt_TargetArea;
    Button btn_Recovery,btn_Cancel,btn_Execute;
    String AgvServerURL="http://192.168.10.26/cms/services/rest/hikRpcService/";
    /*定义一个业务接口,主程序负责实现，所以需在主程序implements中加上这个接口的引用>>>>>切记<<<<<<
    该Fragment所在Activity需要实现该接口
    该Fragment将通过此接口与它所在的Activity交互*/

    private ProgressDialog waitDialog = null;

    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }



    public FragmentO() {
        // Required empty public constructor
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerO(new MainActivity.OnTransParamsListenerO() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d(TAG,"LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            Log.d(TAG,"LoginParam------------------>2");
                        }
                        if (paramComm.equals("RefreshRACK")==true){
                            System.out.println("自动刷新区域内容");
                            refreshAreaData();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    //获取疵点类型;
    private void refreshAreaData() {
        try {
            itemTypeJSON = new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String SqlComm="Exec KeyPoint_AGV_GetTask @OPERTYPE='AREATASK',@Power='ALL',@LoginUserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
        //执行SQL过程
        SqlComm="Exec KeyPoint_AGV_GetArea @OPERTYPE='AREADETAIL',@Power='ALL',@LoginUserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);


    }



    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        System.out.println(TAG+"_onCreateView:0");
        View root = inflater.inflate(R.layout.fragment_o, container, false);
        System.out.println(TAG+"_onCreateView:1");
        InitView(root);
        System.out.println(TAG+"_onCreateView:2");
        return root;
    }

    //初始化;
    public void InitView(View view){
        System.out.println("FragmentO:InitView--Start");
        txt_SourceArea=view.findViewById(R.id.txt_SourceArea);
        txt_TargetArea=view.findViewById(R.id.txt_TargetArea);
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        lv_task=view.findViewById(R.id.lv_task);
        lv_task.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                AlertDialog alertDialog = null; // 创建对话框
                try {
                    selTaskIndex=i;
                    alertDialog = new AlertDialog.Builder(view.getContext())
                            .setTitle("系统提示").setMessage("您定在要取消"+taskJson.optJSONObject(i).getString("TaskCode")+"任务？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    System.out.println("发送取消任务!");
                                    if ((taskJson.optJSONObject(selTaskIndex).has("ReqCode")==true)&&(taskJson.optJSONObject(selTaskIndex).has("TaskCode")==true)) {
                                        try {
                                            PutCancelAGVTask(taskJson.optJSONObject(selTaskIndex).getString("ReqCode"),taskJson.optJSONObject(selTaskIndex).getString("TaskCode"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }

                            }).setNegativeButton("取消",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                alertDialog.show(); // 显示对话框
                return false;
            }
        });
        System.out.println("FragmentO:InitView--1");
        lineGrid=view.findViewById(R.id.lineGrid);
        lineGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    if (lineJson.optJSONObject(i).has("AreaCode")==true) {
                        selLinePlace="";
                        if (lineJson.optJSONObject(i).getString("AreaCode").equals(txt_TargetArea.getText().toString())==false) {
                            txt_TargetArea.setText(lineJson.optJSONObject(i).getString("AreaCode"));
                            selLinePlace=lineJson.optJSONObject(i).getString("AreaCode");
                        }
                        else txt_TargetArea.setText("---");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("FragmentO:InitView--2");
        lineGrid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                //显示货架内容
                try {
                    curAreaCode=lineJson.optJSONObject(i).getString("AreaCode");
                    GetRackDetail(lineJson.optJSONObject(i).getString("AreaCode"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
        System.out.println("FragmentO:InitView--3");
        storageGrid=view.findViewById(R.id.storageGrid);
        storageGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try {
                    if (storageJson.optJSONObject(i).getString("AreaCode").equals(txt_SourceArea.getText().toString())==false) {
                        txt_SourceArea.setText(storageJson.optJSONObject(i).getString("AreaCode"));
                        selHousePlace=storageJson.optJSONObject(i).getString("AreaCode");
                    }
                    else txt_SourceArea.setText("---");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("FragmentO:InitView--4");
        storageGrid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                //显示货架内容
                try {
                    curAreaCode=storageJson.optJSONObject(i).getString("AreaCode");
                    GetRackDetail(storageJson.optJSONObject(i).getString("AreaCode"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
        System.out.println("FragmentO:InitView--5");
        btn_Refresh=view.findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);


        btn_Recovery=view.findViewById(R.id.btn_Recovery);
        btn_Recovery.setOnClickListener(this);
        btn_Cancel=view.findViewById(R.id.btn_Cancel);
        btn_Cancel.setOnClickListener(this);
        btn_Execute=view.findViewById(R.id.btn_Execute);
        btn_Execute.setOnClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        //提示框pd=new ProgressDialog(this);
        waitDialog = new ProgressDialog(getActivity());
        waitDialog.setTitle(getString(R.string.SystemHint));
        System.out.println("FragmentO:InitView--Over");

    }


    private void GetRackDetail(String paramRackCode) {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_AGV_GetRackDetail @RackCode='"+paramRackCode+"',@OPERTYPE='RACKDETAIL',@LoginUserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    private void PutCancelAGVTask(String paramReqCode, String paramTaskCode){
        try {
            //取消任务开始
            //执行SQL过程
            UUID uuid = UUID.randomUUID();
            String tmpUUID=uuid.toString();
            tmpUUID=tmpUUID.replaceAll("-","");
            System.out.println (uuid);
            CancelAGVTaskSQL(paramReqCode,tmpUUID,"Start");

            if (paramTaskCode.length()>0) {
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("reqCode", tmpUUID);
                jsonParam.put("reqTime", "");
                jsonParam.put("clientCode", "");
                jsonParam.put("tokenCode", "");
                jsonParam.put("interfaceName", "cancelTask");
                jsonParam.put("agvCode", "");
                jsonParam.put("taskCode", paramTaskCode);
                System.out.println(jsonParam);
                //提交参数;
                txt_HintInfo.setText("准备提交AGV取消任务请求...");
                sendCancelJsonPost(AgvServerURL, "cancelTask", jsonParam.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //更新SQL
    private void CancelAGVTaskSQL(String paramReqCode,String paramNewReqCode,String paramType) {

        String SqlComm="Exec KeyPoint_AGV_CancelTask @ReqCode='"+paramReqCode+"',@NewReqCode='"+paramNewReqCode+"',@OPERTYPE='"+paramType+"',@LoginUserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    public void sendCancelJsonPost(String serviceUrl, String methodName, String Json) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("Json",Json);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected String doInBackground(Map<String, Object>... params) {
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                String Json= (String) params[0].get("Json");
                // HttpClient 6.0被抛弃了
                String result = null;
                BufferedReader reader = null;
                try {
                    System.out.println("sendCancelJsonPost:"+methodName);
                    String urlPath = serviceUrl + methodName;
                    Log.e("sendCancelJsonPost",urlPath);
                    URL url = new URL(urlPath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("User-Agent","");
                    // 设置文件类型:
                    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    // 设置接收类型否则返回415错误
                    //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
                    conn.setRequestProperty("accept", "application/json");
                    // 往服务器里面发送数据
                    if (Json != null && !TextUtils.isEmpty(Json)) {
                        byte[] writebytes = Json.getBytes();
                        // 设置文件长度
                        conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                        OutputStream outwritestream = conn.getOutputStream();
                        outwritestream.write(Json.getBytes());
                        outwritestream.flush();
                        outwritestream.close();
                        Log.d("hlhupload", "doJsonPost: conn-----" + conn.getResponseCode());
                    }
                    if (conn.getResponseCode() == 200) {
                        reader = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()));
                        result = reader.readLine();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println(result);
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null) {
                    txt_HintInfo.setText("调用失败!");
                    return;
                }
                //这部分主要用于UI更新;
                System.out.println("onPostExecute:"+s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    //这部分主要用于UI更新;
                    System.out.println("onPostExecute:"+s);
                    try {
                        if (jsonObject.has("data")&&jsonObject.has("message")&&jsonObject.has("reqCode")){
                            CancelAGVTaskSQL("",jsonObject.getString("reqCode"),"Over");
                            if (jsonObject.getString("message").equals("成功")) {
                                txt_HintInfo.setText("AGV调度指令发送成功!");
                            }
                            curToast.setText(jsonObject.getString("message"));
                            curToast.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }.execute(params);

    }

    //呼叫AGV
    private void GetCallPath(String paramLinePlace, String paramHousePlace) {
        //调用过程获取路径
        System.out.println("getDepartment------------------------------------->");
        try {
            pathJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_AGV_GetPath @OPERTYPE='GETPATH',@LinePlace='"+paramLinePlace+"',@HousePlace='"+paramHousePlace+"',@DepartNo='"+curDepartNo+"',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }
    //呼叫AGV
    private void AGVRecOK(String paramReqCode, String paramTaskCode) {
        //调用过程获取路径
        System.out.println("getDepartment------------------------------------->");
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_AGV_CallBack @OPERTYPE='AGVREC',@ReqCode='"+paramReqCode+"',@TaskCode='"+paramTaskCode+"',@DepartNo='"+curDepartNo+"',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }


    private void PutAGVTask(String paramReqCode,String paramStartPlace,String paramEndPlace){
        try {
            JSONArray positionCodePath=new JSONArray("[]");
            JSONObject codePath = new JSONObject();
            codePath.put("positionCode",paramStartPlace);
            codePath.put("type","00");
            positionCodePath.put(codePath);
            codePath = new JSONObject();
            codePath.put("positionCode",paramEndPlace);
            codePath.put("type","00");
            positionCodePath.put(codePath);
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("reqCode", paramReqCode);
            jsonParam.put("reqTime", "");
            jsonParam.put("tokenCode", "");
            jsonParam.put("interfaceName", "genAgvSchedulingTask");
            jsonParam.put("taskTyp", "F01");
            jsonParam.put("wbCode", "");
            jsonParam.put("positionCodePath", positionCodePath);
            jsonParam.put("podCode", "");
            jsonParam.put("podDir", "");
            jsonParam.put("priority", "");
            jsonParam.put("agvCode", "");
            jsonParam.put("taskCode", "");
            jsonParam.put("data", "");
            System.out.println(jsonParam);
            //提交参数;
            sendJsonPost(AgvServerURL,"genAgvSchedulingTask",jsonParam.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void sendJsonPost(String serviceUrl, String methodName, String Json) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("Json",Json);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected String doInBackground(Map<String, Object>... params) {
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                String Json= (String) params[0].get("Json");
                // HttpClient 6.0被抛弃了
                String result = null;
                BufferedReader reader = null;
                try {
                    System.out.println("sendCancelJsonPost:"+methodName);
                    String urlPath = serviceUrl + methodName;
                    Log.e("sendCancelJsonPost",urlPath);
                    URL url = new URL(urlPath);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("User-Agent","");
                    // 设置文件类型:
                    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    // 设置接收类型否则返回415错误
                    //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
                    conn.setRequestProperty("accept", "application/json");
                    // 往服务器里面发送数据
                    if (Json != null && !TextUtils.isEmpty(Json)) {
                        byte[] writebytes = Json.getBytes();
                        // 设置文件长度
                        conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                        OutputStream outwritestream = conn.getOutputStream();
                        outwritestream.write(Json.getBytes());
                        outwritestream.flush();
                        outwritestream.close();
                        Log.d("hlhupload", "doJsonPost: conn-----" + conn.getResponseCode());
                    }
                    if (conn.getResponseCode() == 200) {
                        reader = new BufferedReader(
                                new InputStreamReader(conn.getInputStream()));
                        result = reader.readLine();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println(result);
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null) {
                    txt_HintInfo.setText("调用失败!");
                    return;
                }
                //这部分主要用于UI更新;
                System.out.println("onPostExecute:"+s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("data")&&jsonObject.has("message")&&jsonObject.has("reqCode")){
                        if (jsonObject.getString("message").equals("成功")) {
                            //调用任务成功回调;
                            AGVRecOK(jsonObject.getString("reqCode"), jsonObject.getString("data"));
                            //最后一条命令则给上调用成功;
                            if (pathJSON!=null) {
                                if (curAgvReqIndex == pathJSON.length() - 1)
                                    txt_HintInfo.setText("AGV调度指令发送成功-"+jsonObject.getString("message"));
                                else txt_HintInfo.setText("AGV调度准备发送第" + curAgvReqIndex + '条');
                            }
                            curToast.setText(jsonObject.getString("message"));
                            curToast.show();
                        } else {
                            txt_HintInfo.setText("AGV调用失败！");
                            if (jsonObject.has("message")) {
                                curToast.setText(jsonObject.getString("message"));
                                curToast.show();
                            }

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }.execute(params);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_Refresh:
                refreshAreaData();
                break;
            case R.id.btn_Recovery:
                if (txt_TargetArea.getText().toString().equals("---")==false) {
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                            .setTitle(getString(R.string.SystemHint)).setMessage("您确定要执行货架回收操作？")
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    txt_HintInfo.setText("空架回收,获取AGV路径.....");
                                    GetCallPath(txt_TargetArea.getText().toString(), selHousePlace);
                                }
                            }).setNegativeButton(getString(R.string.Cancel),
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                } else {
                    curToast.setText("请在缝制区选择需回收的货架位!");
                    curToast.show();
                }
                break;
            case R.id.btn_Cancel:
                if ((txt_SourceArea.getText().toString().equals("---")==false)&&(txt_TargetArea.getText().toString().equals("---")==false)){
                    curToast.setText("只能先择一个需清除绑定的货架区域!");
                    curToast.show();
                    return;
                }
                if ((txt_SourceArea.getText().toString().equals("---")==false)||(txt_TargetArea.getText().toString().equals("---")==false)) {
                    if ((txt_SourceArea.getText().toString().equals("---")==false)&&(txt_TargetArea.getText().toString().equals("---")==true)) SelAreaCode=txt_SourceArea.getText().toString();
                    else SelAreaCode=txt_TargetArea.getText().toString();
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                            .setTitle(getString(R.string.SystemHint)).setMessage("您确定要执行货加回收操作？")
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    //发送SQL语句更新状态;
                                    txt_HintInfo.setText("清除货架绑定.....");
                                    ClearRackBind(SelAreaCode);
                                }
                            }).setNegativeButton(getString(R.string.Cancel),
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                } else {
                    curToast.setText("请在缝制区选择需清除绑定的货架区域!");
                    curToast.show();
                }
                break;
            case R.id.btn_Execute:
                if ((txt_SourceArea.getText().toString().equals("---")==false)&&(txt_TargetArea.getText().toString().equals("---")==false)) {
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                            .setTitle(getString(R.string.SystemHint)).setMessage("您确定要执行配送操作？")
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    //发送SQL语句更新状态;
                                    txt_HintInfo.setText("执行配送,获取AGV路径.....");
                                    GetCallPath(txt_TargetArea.getText().toString(),txt_SourceArea.getText().toString());
                                }
                            }).setNegativeButton(getString(R.string.Cancel),
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                } else {
                    curToast.setText("请在缝制区及配送区选择位置!");
                    curToast.show();
                }
                break;
            default:
                break;
        }
    }

    //清除货架绑定
    private void ClearRackBind(String paramAreaCode) {
        //执行SQL过程
        String SqlComm = "Exec KeyPoint_AGV_ClearBind @OPERTYPE='CLEARBIND',@AreaCode='"+paramAreaCode+"',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        ReadSQLData(SqlComm);
    }

    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_ERRMSG:
                        //提示提交完成，需确认;
                        Bundle bundle1=msg.getData();
                        String resultMsg=bundle1.getString("Hint");
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                                .setTitle("系统提示").setMessage(resultMsg)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    case MSG_GETPATH:
                        if (pathJSON!=null){
                            if (pathJSON.length()>0){
                                if (pathJSON.optJSONObject(0).has("ReqCode")&&pathJSON.optJSONObject(0).has("StartPlace")&&pathJSON.optJSONObject(0).has("EndPlace")){
                                    curAgvReqIndex=0;
                                    try {
                                        PutAGVTask(pathJSON.optJSONObject(curAgvReqIndex).getString("ReqCode"),
                                                pathJSON.optJSONObject(curAgvReqIndex).getString("StartPlace"),
                                                pathJSON.optJSONObject(curAgvReqIndex).getString("EndPlace"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        break;
                    case MSG_AGVREC:
                        //可以通过回调成功来继续后面任务;
                    case MSG_PUTNEXT:
                        if (curAgvReqIndex<pathJSON.length()-1){
                            curAgvReqIndex++;
                            try {
                                PutAGVTask(pathJSON.optJSONObject(curAgvReqIndex).getString("ReqCode"),
                                        pathJSON.optJSONObject(curAgvReqIndex).getString("StartPlace"),
                                        pathJSON.optJSONObject(curAgvReqIndex).getString("EndPlace"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    case MSG_AREADETAIL:
                        if (areaJSON!=null){
                            //数据分解;
                            try {
                                lineJson=new JSONArray("[]");
                                storageJson=new JSONArray("[]");
                                for (int i=0;i<areaJSON.length();i++){
                                    if (areaJSON.optJSONObject(i).has("AreaType")==true){
                                        if (areaJSON.optJSONObject(i).getString("AreaType").toUpperCase().equals("LINE")){
                                            lineJson.put(areaJSON.optJSONObject(i));
                                        }
                                        if (areaJSON.optJSONObject(i).getString("AreaType").toUpperCase().equals("STORAGE")){
                                            storageJson.put(areaJSON.optJSONObject(i));
                                        }
                                    }
                                }
                                DetailGridAdapter lineGridAdapter=new DetailGridAdapter(getContext());
                                lineGridAdapter.jsonArray=lineJson;
                                lineGrid.setAdapter(lineGridAdapter);
                                DetailGridAdapter storageGridAdapter=new DetailGridAdapter(getContext());
                                storageGridAdapter.jsonArray=storageJson;
                                storageGrid.setAdapter(storageGridAdapter);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    case MSG_RACKDETAIL:
                        if (rackDetailJSON!=null) showPlaceDetail(rackDetailJSON);
                        break;
                    case MSG_TASK:
                        if (taskJson!=null){
                            TaskListAdapter taskListAdapter=new TaskListAdapter(getContext());
                            lv_task.setAdapter(taskListAdapter);
                        }
                        break;
                    case MSG_CLEARBIND:
                        txt_HintInfo.setText("清除绑定成功!");
                        refreshAreaData();
                        break;
                    default:
                        break;
                }
            }
        }
    };

    //显示工序选择
    private void showPlaceDetail(final JSONArray ParamJson){
        if (ParamJson==null) {
            curToast.setText("没有明细数据!");
            curToast.show();
            return;
        }
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"OrderNo\",\"TitleText\":\"合同\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"StyleNo\",\"TitleText\":\"款号\",\"TxtSize\":18,\"TxtWidth\":150,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Color\",\"TitleText\":\"颜色\",\"TxtSize\":18,\"TxtWidth\":200,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Size\",\"TitleText\":\"尺码\",\"TxtSize\":18,\"TxtWidth\":50,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Barcode\",\"TitleText\":\"条码\",\"TxtSize\":18,\"TxtWidth\":100,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"Number\",\"TitleText\":\"件数\",\"TxtSize\":18,\"TxtWidth\":50,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"State\",\"TitleText\":\"状态\",\"TxtSize\":18,\"TxtWidth\":50,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="货架明细列表";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(getContext());
        selectTempletListAdapter.selectJson=ParamJson;
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        NeedClearRack="";
                    }

                }
        ).setNeutralButton("清空", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //弹出对话框，是否要清空
                NeedClearRack="YES";
                //刷新界面;
                Message msg = new Message();
                msg.what = MSG_NEEDCLEAR;
                fragmentHandler.removeMessages(msg.what);
                fragmentHandler.sendMessage(msg);
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        params.width =950;
        params.height = 600 ;
        alterDialog.getWindow().setAttributes(params);
    }
    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        private JSONArray selectJson;
        @Override
        public int getCount() {
            //每页行数
            return selectJson.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<selectJson.length())
                    return selectJson.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,45));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<selectJson.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (selectJson.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = selectJson.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (selectJson.optJSONObject(curPosition).has(TitleName)==true) tmpValue= selectJson.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }

    //订单表格适配器;
    public final class DetailGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        private JSONArray jsonArray;

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return jsonArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_n_item, null, false);
            int color = getResources().getColor(R.color.text_main);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (jsonArray.optJSONObject(position).has("ConColor")==true){
                    color=GetColorValue(jsonArray.optJSONObject(position).getString("ConColor"));
                    (convertView.findViewById(R.id.itemLayout)).setBackgroundColor(color);
                }
                TextView tv = convertView.findViewById(R.id.item_AreaCode);// 显示文字
                if (jsonArray.optJSONObject(position).has("AreaCode")==true)
                    tv.setText(jsonArray.optJSONObject(position).get("AreaCode").toString());
                tv = convertView.findViewById(R.id.item_RackCode);// 显示文字
                if (jsonArray.optJSONObject(position).has("RackCode")==true)
                    tv.setText(jsonArray.optJSONObject(position).get("RackCode").toString());
                tv = convertView.findViewById(R.id.item_OrderNo);// 显示文字
                if (jsonArray.optJSONObject(position).has("OrderNo")==true)
                    tv.setText(jsonArray.optJSONObject(position).get("OrderNo").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }

    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }

    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true) {
                            System.out.println("OPERTYPE:" + jsonArray.optJSONObject(0).getString("OPERTYPE"));
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("TASK")) {
                                taskJson = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_TASK;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }

                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("DETAIL"))
                            {
                                detailJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_DETAIL;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("GETPLACE"))
                            {
                                placeJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_GETPLACE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("GETPATH"))
                            {
                                pathJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_GETPATH;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("AGVREC"))
                            {
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_AGVREC;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("AREADETAIL"))
                            {
                                areaJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_AREADETAIL;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("AREATASK")) {
                                taskJson = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_TASK;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("RACKDETAIL"))
                            {
                                rackDetailJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_RACKDETAIL;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("CLEARAREA"))
                            {
                                refreshAreaData();
                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("CLEARBIND")){
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_CLEARBIND;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            Message message = new Message();
                            message.what = MSG_ERRMSG;
                            Bundle bundle = new Bundle();
                            bundle.putString("Hint", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            message.setData(bundle);
                            fragmentHandler.sendMessage(message);
                        }

                    } else {
                        Message message = new Message();
                        message.what = MSG_ERRMSG;
                        Bundle bundle = new Bundle();
                        bundle.putString("Hint", "未返回任何数据!");
                        fragmentHandler.removeMessages(message.what);
                        fragmentHandler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = MSG_ERRMSG;
                    Bundle bundle = new Bundle();
                    bundle.putString("Hint", e.getMessage().toString());
                    message.setData(bundle);
                    fragmentHandler.sendMessage(message);
                }

            }

        };
        new Thread(run).start();
    }


    //订单表格适配器;
    public final class TaskListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public TaskListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return taskJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return taskJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            TaskListAdapter.ViewHolder holder = null;
            //if (convertView == null) {
            holder=new TaskListAdapter.ViewHolder();
            convertView = inflater.inflate(R.layout.fragment_l_tasklist, null, false);
            holder.btn_TaskCancel=convertView.findViewById(R.id.btn_TaskCancel);
            //} else {
            //    holder = (ViewHolder)convertView.getTag();
            //}
            holder.btn_TaskCancel.setTag(position);
            //给Button添加单击事件  添加Button之后ListView将失去焦点  需要的直接把Button的焦点去掉
            holder.btn_TaskCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showTaskCancel(position);
                }
            });
            int color = getResources().getColor(R.color.text_main);
            String tmpValue;
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (taskJson.optJSONObject(position).has("ConColor")==true) {
                    tmpValue = taskJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                TextView tv = convertView.findViewById(R.id.item_TaskTime);// 显示文字
                if (taskJson.optJSONObject(position).has("TaskTime")==true)
                    tv.setText(taskJson.optJSONObject(position).get("TaskTime").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.item_TaskCode);// 显示文字
                if (taskJson.optJSONObject(position).has("TaskCode")==true)
                    tv.setText(taskJson.optJSONObject(position).get("TaskCode").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.item_TaskInfo);// 显示文字
                if (taskJson.optJSONObject(position).has("TaskInfo")==true)
                    tv.setText(taskJson.optJSONObject(position).get("TaskInfo").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.item_TaskState);// 显示文字
                if (taskJson.optJSONObject(position).has("TaskState")==true)
                    tv.setText(taskJson.optJSONObject(position).get("TaskState").toString());
                tv.setTextColor(color);
                if (taskJson.optJSONObject(position).has("AllowCancel")==true)
                    if (taskJson.optJSONObject(position).get("AllowCancel").toString().equals("Y")){
                        (convertView.findViewById(R.id.btn_TaskCancel)).setBackground(getResources().getDrawable(R.drawable.btn_back_orange));
                        (convertView.findViewById(R.id.btn_TaskCancel)).setEnabled(true);
                    } else {
                        (convertView.findViewById(R.id.btn_TaskCancel)).setBackground(getResources().getDrawable(R.drawable.btn_back_gray));
                        (convertView.findViewById(R.id.btn_TaskCancel)).setEnabled(false);
                    }
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailGridAdapter_position:"+position);
            return convertView;
        }

        private void showTaskCancel(int position) {
            AlertDialog alertDialog = null; // 创建对话框
            try {
                selTaskIndex=position;
                alertDialog = new AlertDialog.Builder(getContext())
                        .setTitle("系统提示").setMessage("您定在要取消"+taskJson.optJSONObject(position).getString("TaskCode")+"任务？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                System.out.println("发送取消任务!");
                                if ((taskJson.optJSONObject(selTaskIndex).has("ReqCode")==true)&&(taskJson.optJSONObject(selTaskIndex).has("TaskCode")==true)) {
                                    try {
                                        PutCancelAGVTask(taskJson.optJSONObject(selTaskIndex).getString("ReqCode"),taskJson.optJSONObject(selTaskIndex).getString("TaskCode"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                            }

                        }).setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            alertDialog.show(); // 显示对话框
        }

        //提取出来方便点
        public final class ViewHolder {
            public Button btn_TaskCancel;
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden==false){
            refreshAreaData();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");

        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }
}